package com.ruoyi.common.ofbiz;

import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.webapp.WebAppUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;

public abstract class OfbizBaseService {

    private ServletContext servletContext = null;
    private Delegator delegator = null;
    private LocalDispatcher dispatcher = null;

    private void init(){
        if(servletContext == null){
            servletContext = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();
        }
    }
    // 在Controller中尽量不操作实体的更新和删除,将这些放在ofbiz的服务里去,查询可以
    // 如果确实要这样做,要手动开启事务
    public Delegator getDelegator() {
        init();
        //ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //ServletContext servletContext = requestAttributes.getRequest().getServletContext();
        if (delegator == null) {
            delegator = (Delegator) servletContext.getAttribute("delegator");
            if (delegator == null) {
                delegator = WebAppUtil.getDelegator(servletContext);
            }
        }
        return delegator;
    }

    public LocalDispatcher getDispatcher() {
        init();
        if (dispatcher == null) {
            dispatcher = (LocalDispatcher) servletContext.getAttribute("dispatcher");
            if (dispatcher == null) {
                dispatcher = WebAppUtil.getDispatcher(servletContext);
            }
        }
        return dispatcher;
    }

}
